import { ComponentProps, useEffect, useMemo, CSSProperties } from 'react';
import Taro, { FC, useDidHide, useDidShow } from '@tarojs/taro';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import { View } from '@tarojs/components';
import LicensePopView from '@/container/LicensePopView';
import NavigationBar from '../NavigationBar';
import SafeAreaView from '../SafeAreaView';
import GlobalModal from '@/container/GlobalModal';

const dstyle = GStyleSheet.create({
  container: {
    width: '100vw',
    minHeight: '100%',
    backgroundSize: 'cover',
    overflow: 'hidden',
    backgroundColor: DynamicColors.screenBackgroundGaryColor,
    boxSizing: 'border-box',
  },
});

interface IProps extends ComponentProps<typeof NavigationBar> {
  backgroundImgSrc?: string;
  style?: CSSProperties;
  onShow?: Function;
  onHide?: Function;
  className?: string;
  safeArea?: boolean;
  navbarBackground?: string;
  title?: string;
  backIcon?: string;
  back?: boolean;
  isTab?: boolean;
  containerStyle?: CSSProperties;
}

const PageContainer: FC<IProps> = ({
  back = true,
  onShow,
  style,
  onHide,
  title,
  children,
  safeArea = true,
  renderRight,
  backgroundImgSrc,
  navbarBackground,
  className,
  backIcon,
  isTab = false,
  containerStyle,
  reLaunch = false,
}) => {
  const styles = dstyle.useDynamicStyle();

  useEffect(() => {
    Taro.setNavigationBarColor({
      backgroundColor: DynamicColors.navBarColor.value,
      frontColor: DynamicColors.frontColor.value,
    });
  }, []);

  useDidShow(() => {
    if (onShow) {
      onShow();
    }
  });

  useDidHide(() => {
    if (onHide) {
      onHide();
    }
  })

  // 获取系统信息
  const systemInfo = useMemo(() => {
    return Taro.getSystemInfoSync();
  }, []);
  // 胶囊按钮位置信息
  const menuButtonInfo = useMemo(() => {
    return Taro.getMenuButtonBoundingClientRect();
  }, []);

  const navBarHeight =
    (menuButtonInfo.top - (systemInfo.statusBarHeight ?? 0)) * 2 +
    menuButtonInfo.height +
    (systemInfo.statusBarHeight ?? 0);

  const ViewCom = safeArea ? SafeAreaView : View;

  return (
    <View
      style={{
        ...styles.container,
        height: systemInfo.screenHeight,
        backgroundImage: `url(${backgroundImgSrc})`,
        ...style,
      }}
      className={className}>
      <NavigationBar
        reLaunch={reLaunch}
        backIcon={backIcon}
        back={back}
        title={title}
        renderRight={renderRight}
        style={{ background: navbarBackground }}
      />
      <ViewCom
        style={{
          paddingTop: navBarHeight,
          height: systemInfo.windowHeight,
          boxSizing: 'border-box',
          ...containerStyle,
        }}>
        {children}
      </ViewCom>
      <GlobalModal />
      <LicensePopView isTab={isTab} />
    </View>
  );
};

export default PageContainer;
